package com.loong.web.gp4j.component.intercept;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;

import com.loong.tool.secret.base.Base64;
import com.loong.tool.secret.base.UTF8;
import com.loong.web.gp4j.service.message.UserMessageService;
import com.loong.web.suppert.auth.UserSessions;
import com.loong.web.suppert.intercept.request.RequestParamSetter;

/**
 * 参数添加组件
 *
 * @author 张成轩
 */
public class ParamSetterComponent implements RequestParamSetter {

	/** */
	private static final String ATTR_PROJECT = "_project";
	/** 网站标题参数名 */
	private static final String ATTR_TITLE = "_title";
	/** 返回路径参数名 */
	private static final String ATTR_URL = "_url";
	/** 系统版本参数名 */
	private static final String ATTR_VERSION = "_version";
	/** 消息数量参数名 */
	private static final String ATTR_MESSAGE = "_message";

	@Value("${web.name}")
	private String project;
	@Value("${web.title}")
	private String title;
	@Value("${web.version}")
	private String version;

	@Resource
	private UserMessageService userMessageService;

	@Override
	public void setParams(HttpServletRequest request) {

		// 系统名称
		request.setAttribute(ATTR_PROJECT, project);
		// 网站标题
		request.setAttribute(ATTR_TITLE, title);
		// 系统版本
		request.setAttribute(ATTR_VERSION, version);
		// 返回路径
		String back = request.getServletPath();
		if (request.getQueryString() != null)
			back += ('?' + request.getQueryString());
		request.setAttribute(ATTR_URL, Base64.encode(UTF8.getBytes(back)));
		// 用户未读消息数量
		if (UserSessions.getUser(request) != null) {
			request.setAttribute(ATTR_MESSAGE, userMessageService.getUserMessageCount(request));
		}
	}
}
